package cn.elwy.rcp.ui.table.internal;

import org.eclipse.jface.preference.IPreferenceStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.elwy.common.util.JsonUtil;
import cn.elwy.osgi.config.ConfigContext;
import cn.elwy.osgi.config.ConfigPath;
import cn.elwy.rcp.ui.table.TablePlugin;
import cn.elwy.rcp.ui.table.model.TableConfig;
import cn.elwy.rcp.ui.table.model.TableInfo;

public class DefaultConfigFactory {

  private static final Logger logger = LoggerFactory.getLogger(DefaultConfigFactory.class);

  private static final IPreferenceStore store = TablePlugin.getDefault().getPreferenceStore();
  private static final String TABLE_CONFIG_EXT_NAME = "custom.dat";
  private static final String TABLE_INFO_EXT_NAME = "dat";

  private DefaultConfigFactory() {
  }

  public static TableConfig getTableConfig(Object subjectId, String tableId) {
    try {
      String key = getKey(subjectId, tableId, TABLE_CONFIG_EXT_NAME);
      String json = getConfig(key);
      if (json == null || json.trim().isEmpty()) {
        return null;
      }
      return JsonUtil.toObject(json, TableConfig.class);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    return null;
  }

  public static void saveTableConfig(Object subjectId, TableConfig tableConfig) {
    String key = getKey(subjectId, tableConfig.getId(), TABLE_CONFIG_EXT_NAME);
    String json = JsonUtil.toJson(tableConfig, true, "columnFormat");
    setConfig(key, json);
  }

  public static TableInfo getTableInfo(Object subjectId, String tableId) {
    try {
      String key = getKey(subjectId, tableId, TABLE_INFO_EXT_NAME);
      String json = getConfig(key);
      if (json == null || json.trim().isEmpty()) {
        return null;
      }
      return JsonUtil.toObject(json, TableInfo.class);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    return null;
  }

  public static void saveTableInfo(Object subjectId, TableInfo tableInfo) {
    String key = getKey(subjectId, tableInfo.getId(), TABLE_INFO_EXT_NAME);
    String json = JsonUtil.toJson(tableInfo, true, "columnFormat");
    setConfig(key, json);
  }

  private static void setConfig(String key, String value) {
    store.setValue(key, value);
  }

  private static String getConfig(String key) {
    return store.getString(key);
  }

  private static String getKey(Object subjectId, String tableId, String extName) {
    return ConfigPath.getStoreKey(ConfigContext.getTableConfigDir(), subjectId, tableId, extName);
  }
}
